package com.controller;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.action.BorrowAction;
import com.bean.RecordBean;
import com.exception.BorrowException;
import com.exception.DBException;
import com.exception.InstrumentException;
import com.exception.UserException;
import com.util.HandleInfo;
import com.util.Regex;
import com.util.StateInfo;

public class BorrowServlet extends HttpServlet
{

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException
	{
		response.setHeader("pragma", "no-cache");
		response.setHeader("cache-control", "no-cahche");
		
		String userID = request.getParameter("userID");
		String barcode = request.getParameter("barcode");
		String days = request.getParameter("days");
		
		if("".equals(userID) || null==userID || userID.length()!=8 || !Regex.checkUserID(userID))
		{
			HandleInfo.ajax(response, StateInfo.INNER_CONFIRM_FAIL);
			return;
		}
		if("".equals(barcode) || null == barcode || barcode.length() > 45 || !Regex.checkBarcode(barcode))
		{
			HandleInfo.ajax(response, StateInfo.INNER_CONFIRM_FAIL);
			return;
		}
		if("".equals(days) || null==days || !Regex.checkDays(days))
		{
			HandleInfo.ajax(response, StateInfo.INNER_CONFIRM_FAIL);
			return;
		}
		RecordBean recordBean = new RecordBean();
		recordBean.setUserID(userID);
		recordBean.setBarcode(barcode);
		recordBean.setDays(days);
		try
		{
			new BorrowAction().borrowIns(response, recordBean);
		}
		catch (UserException e)
		{
			HandleInfo.ajax(response, e.getMessage());
		}
		catch (DBException e)
		{
			HandleInfo.ajax(response, e.getMessage());
		}
		catch (InstrumentException e)
		{
			HandleInfo.ajax(response, e.getMessage());
		}
		catch (BorrowException e)
		{
			HandleInfo.ajax(response, e.getMessage());
		}
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException
	{
		doGet(request, response);
	}
}
